package cn.falcon.fmobi.console.controller;

import cn.falcon.fmobi.admin.dao.dao.model.ResultSetList;
import cn.falcon.fmobi.biz.exception.AdvertiserValidateException;
import cn.falcon.fmobi.biz.exception.ValidateException;
import cn.falcon.fmobi.biz.service.*;
import cn.falcon.fmobi.biz.vo.AdvertiserParam;
import cn.falcon.fmobi.console.common.RestfulJsonModelAndView;
import cn.falcon.fmobi.console.common.Result;
import cn.falcon.fmobi.console.constant.ParamConstant;
import cn.falcon.fmobi.console.constant.UrlConstant;
import cn.falcon.fmobi.console.exception.CallBackException;
import cn.falcon.fmobi.console.exception.ParamValidateException;
import cn.falcon.fmobi.console.requestparam.AdvertiserQueryParam;
import cn.falcon.fmobi.dao.interceptor.PageParameter;
import cn.falcon.fmobi.dao.model.AdvertiserDetail;
import cn.falcon.fmobi.dao.model.AdvertiserDetailModel;
import cn.falcon.fmobi.dao.model.AdvertiserListModel;
import cn.falcon.fmobi.dao.model.TreeVo;
import cn.falcon.fmobi.dao.util.ConvertObjectUtil;
import cn.falcon.marketing.api.util.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 广告主模块
 *
 * @author yujuan.zhang
 * @from 2017-09-26
 * @since V1.0
 */
@Controller
@RequestMapping(UrlConstant.ADVERTISER_URL)
public class AdvertiserCtrl extends BaseCtrl {

    @Autowired
    private CustomerService customerService;

    /**
     * 新增广告主(只有代理商权限可以)
     *
     * @param advertiserParam 广告主参数列表
     * @return
     * @throws UnsupportedEncodingException
     * @throws ParamValidateException
     */
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView addAdvertiser(@RequestBody AdvertiserParam advertiserParam, HttpSession session)
        throws UnsupportedEncodingException, ParamValidateException {
        // 参数验证
        this.validateAdvertiserParam(advertiserParam);

        // 设置代理商id
        Integer agentId = getLoginUser(session) != null ? getLoginUser(session).getAgentId() : null;
        if (null == agentId || agentId == 0) {
            // 权限不足
            throw new ParamValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_NOT_AUTH.getValue(),
                AdvertiserValidateException.ErrorCode.ADVERTISER_NOT_AUTH.getDesc());
        }

        // 代理商权限 服务费必填
        if (null == advertiserParam.getRebate()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "rebate", "Result.err.miss.parameter");
        }
        if (0 > advertiserParam.getRebate() || 100 <= advertiserParam.getRebate()) {
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER, "rebate", "Result.err.invalid.parameter");
        }

        try {
            AdvertiserDetailModel advertiserDetailModel = customerService.addAdvertiser(advertiserParam, agentId);
            return RestfulJsonModelAndView.buildJsonModelAndView(advertiserDetailModel);
        } catch (ValidateException ex) {
            throw new CallBackException(ex.getCode().getValue(), ex.getCode().getDesc());
        }
    }

    /**
     * 查询广告主信息
     *
     * @param id 广告主id
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public ModelAndView getAdvertiserDetailInfo(@PathVariable Integer id, HttpSession session)
        throws ParamValidateException {
        // 查询广告主id
        Integer advertiserId = getLoginUser(session) != null ? getLoginUser(session).getAdvertiserId() : null;
        // 查询代理商id
        Integer agentId = getLoginUser(session) != null ? getLoginUser(session).getAgentId() : null;

        // 权限验证
        if ((null != advertiserId && 0 != advertiserId && !advertiserId.equals(id)) ||
            (null != agentId && 0 != agentId && !customerService.agentExistAdvertiser(agentId, id))) {
            // 权限不足
            throw new ParamValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_NOT_AUTH.getValue(),
                AdvertiserValidateException.ErrorCode.ADVERTISER_NOT_AUTH.getDesc());
        }

        try {
            AdvertiserDetailModel advertiserDetailModel = customerService.getAdvertiserDetailInfoById(id);
            // 代理商权限
            if (null != agentId) {
                return RestfulJsonModelAndView.buildJsonModelAndView(advertiserDetailModel);
            }
            // 广告主权限
            AdvertiserDetail advertiserDetail = ConvertObjectUtil.beanCopy(advertiserDetailModel, AdvertiserDetail.class);
            return RestfulJsonModelAndView.buildJsonModelAndView(advertiserDetail);
        } catch (ValidateException ex) {
            throw new CallBackException(ex.getCode().getValue(), ex.getCode().getDesc());
        }
    }

    /***
     * 编辑广告主(代理商权限和广告主权限)
     *
     * @param advertiserParam 广告主参数列表
     * @return
     * @throws UnsupportedEncodingException
     * @throws ParamValidateException
     */
    @RequestMapping(method = RequestMethod.PUT)
    public ModelAndView updateAdvertiser(@RequestBody AdvertiserParam advertiserParam, HttpSession session)
        throws UnsupportedEncodingException, ParamValidateException {
        // 参数验证
        if (0 == advertiserParam.getId()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "id", "Result.err.miss.parameter");
        }
        this.validateAdvertiserParam(advertiserParam);

        // 查询广告主id
        Integer advertiserId = getLoginUser(session) != null ? getLoginUser(session).getAdvertiserId() : null;
        // 查询代理商id
        Integer agentId = getLoginUser(session) != null ? getLoginUser(session).getAgentId() : null;
        // 权限验证 如果广告主id不正确 或者 该代理商下不存在该广告主，则不可修改
        if ((null != advertiserId && !advertiserId.equals(advertiserParam.getId())) ||
            (null != agentId && agentId != 0 &&
                !customerService.agentExistAdvertiser(agentId, advertiserParam.getId()))) {
            // 权限不足
            throw new ParamValidateException(AdvertiserValidateException.ErrorCode.ADVERTISER_NOT_AUTH.getValue(),
                AdvertiserValidateException.ErrorCode.ADVERTISER_NOT_AUTH.getDesc());
        }

        // 广告主权限 没有服务费
        if (null != advertiserId && null != advertiserParam.getRebate()) {
            advertiserParam.setRebate(null);
        }

        // 代理商权限
        if (null != agentId && 0 != agentId) {
            // 代理商权限 服务费必填
            if (null == advertiserParam.getRebate()) {
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "rebate", "Result.err.miss.parameter");
            }
            if (0 > advertiserParam.getRebate() || 100 <= advertiserParam.getRebate()) {
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER, "rebate", "Result.err.invalid.parameter");
            }
        }

        try {
            customerService.editAdvertiser(advertiserParam, agentId);
            return RestfulJsonModelAndView.buildJsonModelAndView();
        } catch (ValidateException ex) {
            throw new CallBackException(ex.getCode().getValue(), ex.getCode().getDesc());
        }

    }

    /**
     * 广告主参数列表验证
     *
     * @param advertiserParam 广告主参数列表
     * @throws ParamValidateException
     * @throws UnsupportedEncodingException
     */
    private void validateAdvertiserParam(AdvertiserParam advertiserParam)
        throws ParamValidateException, UnsupportedEncodingException {

        // 企业名称必填
        if (StringUtils.isEmpty(advertiserParam.getCompanyName())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "companyName", "Result.err.miss.parameter");
        }

        // 企业名称长度验证
        if (ValidateUtil.checkStrByteLengthLessThan(advertiserParam.getCompanyName(),
            ParamConstant.ADVERTISER_COMPANY_NAME_LENGTH_MIN) || ValidateUtil
            .checkStrByteLengthMoreThan(advertiserParam.getCompanyName(),
                ParamConstant.ADVERTISER_COMPANY_NAME_LENGTH_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "companyName", "Result.err.invalid.length");
        }

        // 推广网址必填
        if (StringUtils.isEmpty(advertiserParam.getPromotionUrl())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "promotionUrl", "Result.err.miss.parameter");
        }

        // 推广网址长度验证
        if (!StringUtils.isEmpty(advertiserParam.getPromotionUrl()) && ValidateUtil
            .checkStrByteLengthMoreThan(advertiserParam.getPromotionUrl(),
                ParamConstant.ADVERTISER_PROMOTION_URL_LENGTH_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "promotionUrl", "Result.err.invalid.length");
        }

        // 行业分类必填
        if (null == advertiserParam.getIndustryId() || 0 == advertiserParam.getIndustryId()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "industryId", "Result.err.miss.parameter");
        }

        // TODO 行业分类至少细化到二级行业

        // 企业形象名称
        if (!StringUtils.isEmpty(advertiserParam.getCorporateImageName()) && ValidateUtil
            .checkStrByteLengthMoreThan(advertiserParam.getCorporateImageName(),
                ParamConstant.ADVERTISER_CORPORATE_IMAGE_NAME_LENGTH_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "corporateImageName",
                "Result.err.invalid.length");
        }

        // 营业执照图片id 必填
        if (0 == advertiserParam.getBusinessLicense()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "businessLicense", "Result.err.miss.parameter");
        }

        // TODO 营业执照图片id是否存在

        // ICP备案截图图片id 必填
        if (0 == advertiserParam.getIcpRecordChart()) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "icpRecordChart", "Result.err.miss.parameter");
        }

        // TODO ICP备案截图图片id是否存在

        // 行业资质图片数组 长度
        if (null != advertiserParam.getIndustryQualificationImageIdList() &&
            0 != advertiserParam.getIndustryQualificationImageIdList().length) {
            if (advertiserParam.getIndustryQualificationImageIdList().length >
                ParamConstant.ADVERTISER_INDUSTRY_QUALIFICATION_IMAGE_ID_LIST_LENGTH_MAX) {
                throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "industryQualificationImageIdList",
                    "Result.err.invalid.length");
            }
        }

        // TODO 行业资质图片id是否存在

        // 广告资质图片数组 长度
        if (null != advertiserParam.getAdQualificationImageIdList() &&
            0 != advertiserParam.getAdQualificationImageIdList().length) {
            if (advertiserParam.getAdQualificationImageIdList().length >
                ParamConstant.ADVERTISER_AD_QUALIFICATION_IMAGE_ID_LIST_LENGTH_MAX) {
                throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "adQualificationImageIdList",
                    "Result.err.invalid.length");
            }
        }

        // TODO 广告资质图片id是否存在

        // 联系人手机号
        if (!StringUtils.isEmpty(advertiserParam.getContactPersonMobile()) && ValidateUtil
            .checkStrByteLengthMoreThan(advertiserParam.getContactPersonMobile(),
                ParamConstant.ADVERTISER_CONTACT_PERSON_MOBILE_LENGTH_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "contactPersonMobile",
                "Result.err.invalid.length");
        }

        // 联系人座机号
        if (!StringUtils.isEmpty(advertiserParam.getContactPersonTelephone()) && ValidateUtil
            .checkStrByteLengthMoreThan(advertiserParam.getContactPersonTelephone(),
                ParamConstant.ADVERTISER_CONTACT_PERSON_TELEPHONE_LENGTH_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "contactPersonTelephone",
                "Result.err.invalid.length");
        }

    }

    /**
     * 广告主列表查询
     *
     * @param advertiserQueryParam 广告主列表查询参数
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getAdvertiserListByPage(AdvertiserQueryParam advertiserQueryParam, HttpSession session) {
        Integer advertiserId = getLoginUser(session) != null ? getLoginUser(session).getAdvertiserId() : null;
        // 设置代理商id
        Integer agentId = getLoginUser(session) != null ? getLoginUser(session).getAgentId() : null;
        // 查询参数列表
        Map<String, Object> searchMap = advertiserQueryParam.getSearchMap();
        searchMap.put("agentId", agentId);
        searchMap.put("id", advertiserId);
        // 分页参数
        PageParameter pageParameter = advertiserQueryParam.getPageInfo();
        // 分页查询
        List<AdvertiserListModel> list = customerService.getAdvertiserListByPage(searchMap, pageParameter);
        return RestfulJsonModelAndView.buildJsonModelAndView(new ResultSetList<>(pageParameter.getTotalCount(), list));
    }

    /**
     * 广告主下拉列表
     *
     * @param session
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "dropList")
    public ModelAndView getAdvertiserDropDownList(HttpSession session) {
        //TODO 需要从登陆session中获取到当前登陆用户
        List<TreeVo> list = null;
        Integer agentId = getLoginUser(session) != null ? getLoginUser(session).getAgentId() : null;
        if (null != agentId && agentId != 0) {
            list = customerService.listAdvertiserByAgencyId(agentId);
        }
        // 跟据登陆用户，查询出登陆用户下所有有效的广告主
        return RestfulJsonModelAndView.buildJsonModelAndView(list);
    }
}
